<?php
/**
 * @authors alex (20779512@qq.com)
 * @date    2014-03-24 16:49:33
 * @version 1.0
 */

class StoreAction extends HomeAction {

    public function _initialize(){
        parent::_initialize();
        $map['memberID']=$this->_user['memberID'];
        $cartNum = M('Cart')->where($map)->count();
        $this->assign('cartNum',$cartNum);
    }

    //商品分类列表
    public function cate(){
        
        $list = M('ShopCate')->select();
        $this->assign('list',$list);
        $this->display();
    }

    //商品列表
    public function index(){        
        $cid=I("cid",0);
        $order=I("order","id")=="time"?"id":I("order","id");
        $method=I("method","desc");
        //当前分类
        if($cid>0){
            $cate=M("ShopCate")->where("id=".$cid."")->find();
            $map['cid']=$cid;
        }else{
            $cate=array("name"=>"全部商品","id"=>0);
        }
        $this->assign("cate",$cate);
        //产品列表
        $map['show']=1;
        $list = M('Goods')->where($map)->order($order." ".$method)->field('id,name,picname,price,shichang,sellNumber')->limit(8)->select();
        $this->assign('list',$list);
        $this->assign('order',$order=="id"?"time":$order);
        $this->assign('method',$method);
        $this->assign('total',M('Goods')->where($map)->count());
        $this->assign('action','index');
        $this->assign('catefocus',"am-icon-focus");
        $this->display();
    }

    //商品搜索页
    public function search(){
        $s=I("s");
        if(!isset($s)){
            $this->error("搜索词为空");
        }else{
            $order=I("order","id")=="time"?"id":I("order","id");
            $method=I("method","desc");
            //当前分类
            $cate=array('name'=>$s,'id'=>0);
            $this->assign("cate",$cate);
            //产品列表
            $map['name']=array("like","%".$s."%");
            $map['show']=1;
            $list = M('Goods')->where($map)->order($order." ".$method)->field('id,name,baoxian,picname,price,shichang,sellNumber')->limit(8)->select();
            foreach($list as $key=>$val){
                $list[$key]['name']=str_replace($s,'<font style="color:#FF0000;font-weight:bold;">'.$s.'</font>',$val['name']);
            }
            $this->assign('list',$list);
            $this->assign('order',$order=="id"?"time":$order);
            $this->assign('method',$method);
            $this->assign('total',M('Shop')->where($map)->count());
            $this->assign('action','search');
            $this->assign('s',$s);
            $this->assign('searchfocus',"am-icon-focus");
            $this->display('index');
        }
    }
    

    //滚动加载
    public function ajaxProducts(){
        $inajax=I("inajax");
        $page=I("page");
        $order=I("order","id")=="time"?"id":I("order","id");
        $method=I("method","desc");
        $pagesize=I("pagesize",10);
        $cid=I("cid");
        $s=I("keys");
        if(isset($cid) && $cid>0){
            $map['cid']=I("cid");
        }
        if(isset($s)){
            $map['name']=array("like","%".$s."%");
        }
        $map['show']=1;
        if($inajax!=1){
            echo $this->echo_json_str("ERROR","数据提交错误");exit;
        }else{
            $limit=($page-1)*$pagesize.','.$pagesize;
            $list = M('Goods')->where($map)->field('id,name,picname,baoxian,price,shichang,sellNumber')->order($order." ".$method)->limit($limit)->select();
            if(isset($s)){
                foreach($list as $key=>$val){
                    $list[$key]['name']=str_replace($s,'<font style="color:#FF0000;font-weight:bold;">'.$s.'</font>',$val['name']);
                }
            }
            echo $this->echo_json_str("SUCCESS",$list);exit;
        }
    }


    //商品详细信息
    public function view(){
        $id = I('get.id');
        $map['id']=$id;
        $list = M('Goods')->where($map)->find();
        if (!$list) {
            $this->error('没有该商品');
        }
        unset($map);
        $map['goodsID']=$id;
        $album = M('GoodsImage')->where($map)->order('sort asc')->select();
        if (!$album) {
            $album = array(
                array(
                    'id'=>0,
                    'picname'=>$list['picname'],
                ),                
            );
        }
        $list['zhekou'] = number_format(($list['price']/$list['shichang'])*10,1);
        $this->assign('album',$album);
        $this->assign('list',$list);

        //商品规格
        if ($list['hasoption']==1) {
            unset($map);
            $map['goodsid']=$list['id'];
            $specs=M("GoodsSpec")->where($map)->order("displayorder asc,id asc")->select();
            foreach($specs as $key=>$val){
                unset($map);
                $map['specid']=$val['id'];
                $specs[$key]['items']=M("GoodsSpecItem")->where($map)->order("displayorder asc,id asc")->select();   
            }
            unset($map);
            $map['goodsid']=$list['id'];
            $options=M("GoodsOption")->where($map)->order("displayorder asc,id asc")->select();
            $this->assign('options',$options);            
            $this->assign('specs',$specs);
        }

        //评论
        unset($map);
        $map['pid']=$id;
        $comment = M("Comment")->where($map)->order('id desc')->limit(3)->select();
        $this->assign('comment',$comment);
        $commentNum = M("Comment")->where($map)->count();
        $this->assign('commentNum',$commentNum);

        //like
        unset($map);
        $map['cid'] = $list['cid'];
        $map['id'] = array('neq',$id);
        $like = M('Goods')->field('id,name,picname,price')->where($map)->limit(3)->select();
        $this->assign('like',$like);

    	$this->display();
    }

    //加入购物车
    public function addcart(){
        $goodsID = I('get.goodsID');
        $optionid = I('get.optionid');
        if ($optionid!="") {
            $map['optionid'] = $optionid;
        }
        $map['memberID'] = $this->_user['memberID'];
        $map['goodsID'] = $goodsID;
        $obj = M('Cart');
        $list = $obj->where($map)->find();
        if ($list) {
            $obj->where($map)->setInc('number'); 
        }else{
            $data['memberID']=$this->_user['memberID'];
            $data['goodsID']=$goodsID;
            $data['optionid']=$optionid;
            $data['number']=1;
            $data['createTime']=time();
            $obj->add($data);
        }
        echo '操作成功';
    }


    //加入收藏
    public function addfav(){
        $goodsID = I('get.goodsID');
        $map['memberID'] = $this->_user['memberID'];
        $map['goodsID'] = $goodsID;
        $obj = M('Fav');
        $list = $obj->where($map)->find();
        if (!$list) {  
            $data['memberID']=$this->_user['memberID'];
            $data['goodsID']=$goodsID; 
            $data['name']=I('get.name'); 
            $data['price']=I('get.price'); 
            $data['picname']=I('get.picname'); 
            $data['createTime']=time();
            $obj->add($data);
        }
        echo '操作成功';
    }

    //购买
    public function buy(){     
        $goodsID = I('get.goodsID');
        $optionid = I('get.optionid');
        if ($optionid!="") {
            $map['optionid'] = $optionid;
        }
        $map['memberID'] = $this->_user['memberID'];
        $map['goodsID'] = $goodsID;
        $obj = M('Cart');
        $list = $obj->where($map)->find();
        if ($list) {
            $obj->where($map)->setInc('number'); 
        }else{
            $data['memberID']=$this->_user['memberID'];
            $data['goodsID']=$goodsID;
            $data['optionid']=$optionid;
            $data['number']=1;
            $data['createTime']=time();
            $obj->add($data);
        }

        redirect(U('Store/cart'));
    }

    //购物车
    public function cart(){
        $map['memberID'] = $this->_user['memberID'];
        $list = M('Cart')->where($map)->select();
        $totalPrice = 0;
        foreach ($list as $key => $value) {
            $goods = M('Goods')->where('id='.$value['goodsID'])->find();            
            if ($goods) {
                $list[$key]['pname'] = $goods['name'];
                $list[$key]['picname'] = $goods['picname'];
                //读取参数
                if ($value['optionid']>0) {
                    $pram = M('GoodsOption')->where('id='.$value['optionid'])->find();
                    $list[$key]['price'] = $pram['productprice'];
                    $totalPrice = $totalPrice + $pram['productprice']*$value['number'];
                    $list[$key]['pram'] = $pram['title'];
                }else{
                    $list[$key]['price'] = $goods['price'];
                    $totalPrice = $totalPrice + $goods['price']*$value['number'];
                }                
                $totalPrice = number_format($totalPrice, 2, '.', '');
            }            
        }
        $this->assign('totalPrice',$totalPrice);
        $this->assign('list',$list);

        $empty = '<div class="empty"><img src="'.RES.'/image/icon_cart_empty.png"><p>您的购物车空空如也，赶紧去选购吧~~</p></div>';
        $this->assign('empty',$empty);   

    	$this->display();
    }

    //设置购物数量
    public function setCartNum(){
        $map['memberID'] = $this->_user['memberID'];
        $map['id'] = I('get.cartID');
        $data['number'] = I('get.number');
        $obj = M('Cart');
        $obj->where($map)->setField($data); 
    }

    public function delcart(){
        $map['memberID'] = $this->_user['memberID'];
        $map['id'] = I('get.id');
        M('Cart')->where($map)->delete();
        redirect($_SERVER['HTTP_REFERER']);      
    }


    public function order(){
        $map['memberID'] = $this->_user['memberID'];
        $list = M('Cart')->where($map)->select();
        $goodsMoney = 0;
        $hasBaoxian = 0;
        if ($list) {
            foreach ($list as $key => $value) {
                $goods = M('Goods')->field('id,picname,name,price,baoxian')->where('id='.$value['goodsID'])->find();
                if ($goods) {
                    //购物车中的商品是否包含交强险
                    if ($goods['baoxian']==1) {
                        $hasBaoxian++;
                    }


                    $list[$key]['pname'] = $goods['name'];
                    $list[$key]['hasBaoxian'] = $goods['baoxian'];
                    $list[$key]['picname'] = $goods['picname'];
                    $list[$key]['pid'] = $goods['id'];
                    //读取参数
                    if ($value['optionid']>0) {
                        $pram = M('GoodsOption')->where('id='.$value['optionid'])->find();
                        $list[$key]['price'] = $pram['productprice'];
                        $goodsMoney = $goodsMoney + $pram['productprice']*$value['number'];
                        $list[$key]['pram'] = $pram['title'];
                    }else{
                        $list[$key]['price'] = $goods['price'];
                        $goodsMoney = $goodsMoney + $goods['price']*$value['number'];
                    }          
                    $goodsMoney = number_format($goodsMoney, 2, '.', '');
                }
            }

            //物流信息
            unset($map);
            $map['show']=1;
            $dispatch = M('Dispatch')->where($map)->order('sort asc')->select();
            $this->assign('dispatch',$dispatch);

            //收件信息
            unset($map);
            $addID = I('get.addID');
            if ($addID!='') {
                $map['id']=$addID;
            }
            $map['memberID'] = $this->_user['memberID'];
            $address = M('Address')->where($map)->order('def desc , id desc')->find();
            $this->assign('address',$address);

            //4位随机数
            $curDateTime = date("YmdHis");
            $randNum = rand(1000, 9999);
             /* 商家的定单号 */
            $order_no = $curDateTime . $randNum;

            $this->assign('list',$list);
            $this->assign('goodsMoney',$goodsMoney);
            $this->assign('order_no',$order_no);
            $this->assign('hasBaoxian',$hasBaoxian);
            $this->display();
        }else{
            redirect(U('Index/index'));
        }        
    }


    //保存订单
    public function save(){
        $pid = I('post.pid');     
        $picname = I('post.picname');
        $pname = I('post.pname');
        $number = I('post.number');
        $price = I('post.price');     
        $hasBaoxian = I('post.hasBaoxian');     

        $obj = D('Order');
        if ($data = $obj->create()) {  
            if ($obj->add($data)) {

                //保存订单详情
                for ($i=0; $i < count($pname); $i++) {

                    $detail['pid'] = $pid[$i];
                    $detail['picname'] = $picname[$i];
                    $detail['pname'] = $pname[$i];
                    $detail['number'] = $number[$i];
                    $detail['price'] = $price[$i];
                    $detail['hasBaoxian'] = $hasBaoxian[$i];
                    $detail['order_no'] = $data['order_no'];                    
                    $detail['memberID'] = $this->_user['memberID'];
                    $detail['createTime'] = $data['createTime'];
                    M('OrderDetail')->add($detail);

                    M('Goods')->where('id='.$pid[$i])->setInc('sellNumber',$number[$i]);

                    unset($detail);
                }

                //发送管理员通知短信
                if (C('SMS_MOBILE') && C('SMS_SERVER_NOTICE')) {
                    $content = '你有一份新的订单,订单号'.$data['order_no'].',请登录网站查看';
                    $this->send_mobile_sms(C('SMS_MOBILE'),$content);
                }

                //发送客户通知短信
                

                //发送微信通知
                if (C('weixin_id')) {
                    $access_token = $this->get_access_token();
                    $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
                    $wxdata = '{"touser":"'.C('weixin_id').'","msgtype":"text","text":{"content":"你有一份新的订单,订单号'.$data['order_no'].',请登录网站查看"}}';
                    $result = $this->https_post($url,$wxdata);
                }

                //删除购物车
                $map['wxid'] = $this->wxid;
                M('Cart')->where($map)->delete();
                $message = '操作成功 去支付';
                if ($data['payType']==1) {
                    #支付宝支付
                    $url = U('Wap/Alipay/index',array('single_orderid'=>$data['order_no']));
                }else{
                    #微信支付
                    $url = U('Wap/Pay/index',array('single_orderid'=>$data['order_no']));
                }                
                $state = 'SUCCESS';
            } else {
                $state = '操作失败';
            }
        } else {
            $state = $obj->getError();
        }
        echo $this->echo_json_str($state , $message , $url);
    }

    //重新支付
    public function repay(){
        $order_no = I('get.order_no');
        $payType = I('get.payType');
        $map['order_no'] = $order_no;
        $map['memberID'] = $this->_user['memberID'];
        $list = M('Order')->where($map)->find();
        if ($list) {
            if ($list['payStatus']==1) {
                $this->error('订单已经支付成功，不要重复支付');
            }else{

                M('Order')->where($map)->setField('payType',$payType);
                if ($payType==1) {
                    #支付宝支付
                    $url = U('Wap/Alipay/index',array('single_orderid'=>$list['order_no']));
                }else{
                    #微信支付
                    //$url = '/wxpay/index.php?g=Wap&m=Pay&a=index&price='.$list['money'].'&single_orderid='.$list['order_no'];
                    $url = U('Wap/Pay/index',array('single_orderid'=>$list['order_no']));
                }
                header('Location:'.$url); 
            }
        }else{
            $this->error('订单不存在');
        }
    }


    //订单支付成功
    /*public function payReturn(){
        $order_no = I('get.order_no');
        $map['order_no'] = $order_no;
        $list = M('Order')->where($map)->find();        
        if ($list) {
            if ($list['payStatus']==1) {
                exit('该订单已经支付完成，请不要重复操作');
            }else{
                //更新订单状态
                M('Order')->where($map)->setField('payStatus',1);

                unset($map);
                $map['id'] = $list['memberID'];

                //更新会员组
                $obj = M('Member');
                $obj->where($map)->setField('userGroup',1);

                //是否启用佣金
                if (C('yontjin_open')) {
                    //减去物流费用
                    $money = $list['money']-$list['paymentMoney'];
                    //保存佣金记录
                    $this->saveYongjin($list['memberID'] , $list['memberID'] , $money);
                }

                
                $this->display();
            }
        }else{
            exit('订单不存在');
        }
    }   */ 
}